import requests
import argparse
import re
import os
from urllib3.exceptions import InsecureRequestWarning

# 禁用 SSL 验证警告（可选）
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def save_urls_to_file(urls, output_file):
    """将 URL 列表保存到指定文件"""
    try:
        with open(output_file, "w", encoding="utf-8") as f:
            f.write("\n".join(urls))
        return True
    except Exception as e:
        print(f"保存文件失败：{str(e)}")
        return False


def fetch_release_assets(owner, repo, tag, keyword):
    """获取符合条件的所有文件资源"""
    api_url = f"https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}"
    response = requests.get(api_url, verify=False)
    response.raise_for_status()

    assets = response.json().get("assets", [])
    pattern = re.compile(re.escape(keyword), re.IGNORECASE)

    return [
        asset["browser_download_url"]
        for asset in assets
        if pattern.search(asset["name"])
    ]


def main():
    parser = argparse.ArgumentParser(
        description="GitHub Release 文件地址保存工具",
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument("--tag", required=True, help="Release 标签（如 20250311）")
    parser.add_argument(
        "--keyword",
        required=True,
        help="文件名包含的关键字（如 x86_64-pc-windows-msvc-install_only_stripped）",
    )
    parser.add_argument(
        "--owner", default="astral-sh", help="GitHub 仓库拥有者（默认：astral-sh）"
    )
    parser.add_argument(
        "--repo",
        default="python-build-standalone",
        help="GitHub 仓库名称（默认：python-build-standalone）",
    )
    parser.add_argument(
        "-o",
        "--output",
        default="download_urls.txt",
        help="输出文件名（默认：download_urls.txt）",
    )

    args = parser.parse_args()

    try:
        print(f"正在获取 {args.tag} 版本的资源列表...")
        matched_urls = fetch_release_assets(
            args.owner, args.repo, args.tag, args.keyword
        )

        if not matched_urls:
            print(f"未找到包含 '{args.keyword}' 的文件")
            return

        print(f"找到 {len(matched_urls)} 个匹配文件地址")
        if save_urls_to_file(matched_urls, args.output):
            print(f"地址已保存至：{os.path.abspath(args.output)}")
            print("文件内容示例：")
            print(
                "\n".join(matched_urls[:3]) + ("\n..." if len(matched_urls) > 3 else "")
            )

    except requests.exceptions.HTTPError as e:
        print(f"\n错误：{e.response.status_code} - {e.response.reason}")
        if e.response.status_code == 404:
            print("请检查以下内容：")
            print(f"1. 标签 {args.tag} 是否存在？")
            print(f"2. 仓库 {args.owner}/{args.repo} 是否正确？")
    except Exception as e:
        print(f"\n发生错误：{str(e)}")


if __name__ == "__main__":
    main()
